<template>
  <div class="search-suggestion">
    <van-cell
      icon="search "
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <div slot="title" v-html="highlight(text)"></div
    ></van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from "@/api/search";
import { debounce } from "lodash";
export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [],
    };
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(function (value) {
        this.loadSearchSuggestion(value);
      }, 2000),
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestion(q) {
      try {
        const { data } = await getSearchSuggestions(q);
        this.suggestions = data.data.options;
      } catch (error) {
        this.$toast("获取数据失败");
      }
    },
    highlight(text) {
      const highlightStr = `<span style="color:red;">${this.searchText}</span>`;
      const reg = new RegExp(this.searchText, "gi");
      return text.replace(reg, highlightStr);
    },
    onSearch(val) {
      this.searchText = val;
      this.isResultShow = true;
    },
  },
};
</script>

<style scoped lang="less"></style>